package com.rdiot.yx485.ui.main

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.viewpager.widget.ViewPager
import com.drake.net.scope.AndroidScope
import com.drake.net.utils.scopeNetLife
import com.google.android.material.tabs.TabLayout
import com.gyf.immersionbar.ktx.immersionBar
import com.jeremyliao.liveeventbus.LiveEventBus
import com.king.zxing.util.LogUtils
import com.rdiot.yx485.R
import com.rdiot.yx485.base.BaseActivity
import com.rdiot.yx485.base.BaseMainPagerAdapter
import com.rdiot.yx485.base.LocalData
import com.rdiot.yx485.databinding.ActMainBinding
import com.rdiot.yx485.databinding.ItemBottomTabBinding
import com.rdiot.yx485.net.getCurrentUserData
import com.rdiot.yx485.net.getFamilyData
import com.rdiot.yx485.net.getWeather
import com.rdiot.yx485.net.getWelcome
import com.rdiot.yx485.ui.bind.BindActivity
import com.rdiot.yx485.ui.find.FindFragment
import com.rdiot.yx485.ui.home.HomeFragment
import com.rdiot.yx485.ui.login.LoginActivity
import com.rdiot.yx485.ui.login.SetPwdActivity
import com.rdiot.yx485.ui.mine.MineFragment
import com.rdiot.yx485.ui.room.RoomFragment
import com.rdiot.yx485.util.*
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay


/**
 * 主页
 */
@AndroidEntryPoint
class MainActivity : BaseActivity<ActMainBinding>() {
    override fun getLayoutId() = R.layout.act_main
    private var pollJob: Job? = null

    companion object {
        /** 轮询间隔 */
        private const val POLL_REFRESH_TIME = 3
    }

    /** 主菜单（图标） */
    private val mIcons = intArrayOf(
        R.drawable.sel_tab_home,
        R.drawable.sel_tab_room,
//        0,
//        R.drawable.sel_tab_find,
        R.drawable.sel_tab_mine,
    )

    private val mTitles = intArrayOf(
        R.string.home,
        R.string.room,
//        0,
//        R.string.find,
        R.string.mine
    )

    private val mFragments: MutableList<Fragment> = mutableListOf(
        HomeFragment(),
        RoomFragment(),
//        Fragment(),
//        FindFragment(),
        MineFragment()
    )


    override fun initView(savedInstanceState: Bundle?) {
        immersionBar {
            statusBarView(binding.v)
            statusBarColor(R.color.transparent)
            navigationBarColor(R.color.white)
            statusBarDarkFont(true)
        }


        // Token失效监听
        LiveEventBus.get(LoginActivity.TOKEN_INVALID, String::class.java).observe(this) {
            finishGoTo(
                getClearTopIntent(LoginActivity::class.java)
                    .apply {
                        putExtra(LoginActivity.TOKEN_INVALID, true)
                    })
        }


        LocalData.selFamilyId.postValue(null)

        getData()

        initTab()


        binding.ivAdd.setClickAlpha {
            binding.isAddShow = !binding.isAddShow
        }

        binding.llAddRoom.setClickLimitListener {
            binding.isAddShow = false
            clearGoTo(BindActivity::class.java)
        }

        binding.llAddScene.setClickLimitListener {
            binding.isAddShow = false
            LogUtils.i("llAddScene")
        }


        // 首次登录 弹框设置密码
        LocalData.loginData?.let { loginData ->
            if (loginData.appFirstLogin) {
                clearGoTo(SetPwdActivity::class.java)
                loginData.appFirstLogin = false
                loginData.saveLocal()
            }
        }

        LocalData.appVersionData.observe(this) { data -> checkUpdate(data) }
    }

    /** 获取数据 */
    private fun getData() {
        if (LocalData.loginData == null) {
            finishGoTo(LoginActivity::class.java)
        } else {
            scopeNetLife {
                //获取用户信息
                getCurrentUserData().await().also { userData ->
                    LocalData.userData.postValue(userData)
                    //如果用户没有选择家庭，则以默认家庭显示
                    if (LocalData.selFamilyId.value.isNullOrBlank()) {
                        LogUtils.d("未选择家庭，使用默认家ID")
                        LocalData.selFamilyId.postValue(userData.defaultHomeId)
                    }

                    getFamilyData(userData.defaultHomeId).await().also { familyData ->
                        LocalData.familyData.postValue(familyData)
                    }

                    getWeather(userData.defaultHomeId).await().also { weatherData ->
                        LocalData.weatherData.postValue(weatherData)
                    }
                    getWelcome().await().also { welcomeData ->
                        LocalData.welcomeData.postValue(welcomeData)
                    }
                }

                startPoll()
            }
        }
    }


    /** 开始轮询  最低 [POLL_REFRESH_TIME] 间隔*/
    private fun startPoll() {
        if (pollJob == null) {
            var scope: AndroidScope? = null

            pollJob = lifecycleScope.launchWhenResumed {
                while (!isFinishing) {
                    val last = LocalData.lastRefreshTime
                    val less = (POLL_REFRESH_TIME - (curTime - last) / 1000).coerceAtLeast(0)
                    if (less == 0L) {
                        scope?.cancel() // 如果存在则取消
                        scope = scopeNetLife {
                            LocalData.selFamilyId.value?.let {
                                getFamilyData().await().also {
                                    LocalData.familyData.postValue(it)
                                }
                            }
                        }
                        LocalData.lastRefreshTime = curTime
                    }
                    delay(100)
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        LocalData.lastRefreshTime = 0
    }

    fun addCancel(view: View) {
        binding.isAddShow = false
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun initTab() {
        val pagerAdapter = BaseMainPagerAdapter(supportFragmentManager)
        pagerAdapter.setFragments(binding.viewPager, mFragments)
        binding.viewPager.adapter = pagerAdapter
        binding.viewPager.setSmoothScroll(false)
        binding.viewPager.setCanScroll(false)
        binding.viewPager.offscreenPageLimit = mFragments.size
        binding.tabLayout.setupWithViewPager(binding.viewPager)


        binding.viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
            }

            override fun onPageSelected(position: Int) {
//                binding.isAddShow = position == 2
            }

            override fun onPageScrollStateChanged(state: Int) {
            }

        })


        for (i in mFragments.indices) { // 循环添加自定义的tab
            val tab: TabLayout.Tab? = binding.tabLayout.getTabAt(i)
            ItemBottomTabBinding.inflate(LayoutInflater.from(this)).apply {
//                if (i != 2) {
                tabImage.setImageResource(mIcons[i])
                tvTitle.text = getString(mTitles[i])
                tab?.customView = this.root
//                }
            }
        }

//        // 取消中间按钮响应
//        val tabStrip = binding.tabLayout.getChildAt(0) as LinearLayout
//        for (i in 0 until tabStrip.childCount) {
//            if (i == 2) {
//                tabStrip.getChildAt(i).setOnTouchListener { _, _ ->
//                    true
//                }
//            }
//        }
    }

    /** 隐藏底部Tab栏目 */
    fun hideBottomTabBar(hide: Boolean) {
        if (hide) {
            binding.tabLayout.visibility = View.GONE
            binding.ivAdd.visibility = View.GONE
            immersionBar {
                navigationBarColor(R.color.main_bg_color)
            }
        } else {
            binding.tabLayout.visibility = View.VISIBLE
//            binding.ivAdd.visibility = View.VISIBLE
            immersionBar {
                navigationBarColor(R.color.white)
            }
        }
    }

    override fun onBackPressed() {
        moveTaskToBack(true)
    }
}



